package com.spirng.leetcode.day07;
//回溯(最近的公共祖先节点一定是p或q最靠经的根节点的q或p的父节点)
public class Test236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if(root==p||root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null&&right!=null){
            return root;
        }
        if(left!=null&&right==null){
            return left;
        }
        if(left==null&&right!=null){
            return right;
        }
        return null;
    }
}